import React, { useState, useRef } from 'react';
import ParameterCalculator from '../services/ParameterCalculator';
import './TDCAnalyzer.css';

const TDCMarkersPanel = ({ markers, onMarkerUpdate, onClearAllMarkers, chartData, dicomData, frameRange = { start: 1, end: 1 } }) => {
  // 添加名称编辑相关状态
  const [editingMarker, setEditingMarker] = useState(null); // 正在编辑名称的标记ID
  const [editingName, setEditingName] = useState(''); // 临时编辑的名称
  const [selectedMarker, setSelectedMarker] = useState(null);

  // 初始化参数计算器
  const parameterCalculator = useRef(new ParameterCalculator()).current;

  // 批量显示/隐藏标记
  const handleBatchVisibility = (visible) => {
    const updatedMarkers = markers.map(marker => ({
      ...marker,
      visible: visible
    }));
    onMarkerUpdate(updatedMarkers);
  };

  // 切换单个标记的可见性
  const handleToggleVisibility = (markerId) => {
    const updatedMarkers = markers.map(marker => {
      if (marker.id === markerId) {
        return { ...marker, visible: !(marker.visible !== false) };
      }
      return marker;
    });
    onMarkerUpdate(updatedMarkers);
  };

  // 删除单个标记
  const handleDeleteMarker = (markerId) => {
    const updatedMarkers = markers.filter(marker => marker.id !== markerId);
    onMarkerUpdate(updatedMarkers);
    if (selectedMarker === markerId) {
      setSelectedMarker(null);
    }
  };

  // 开始编辑标记名称
  const handleStartEditName = (markerId, currentName) => {
    setEditingMarker(markerId);
    setEditingName(currentName);
  };

  // 保存编辑的名称
  const handleSaveEditName = (markerId) => {
    if (editingName.trim() === '') {
      // 如果名称为空，恢复原名称
      const originalMarker = markers.find(m => m.id === markerId);
      setEditingName(originalMarker?.name || '');
      return;
    }

    const updatedMarkers = markers.map(marker => 
      marker.id === markerId 
        ? { ...marker, name: editingName.trim() }
        : marker
    );
    onMarkerUpdate(updatedMarkers);
    
    // 清空编辑状态
    setEditingMarker(null);
    setEditingName('');
  };

  // 取消编辑名称
  const handleCancelEditName = () => {
    setEditingMarker(null);
    setEditingName('');
  };

  // 处理名称输入框的键盘事件
  const handleNameInputKeyDown = (e, markerId) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSaveEditName(markerId);
    } else if (e.key === 'Escape') {
      e.preventDefault();
      handleCancelEditName();
    }
  };

  // 计算平均通过时间 (MTT) - Mean Transit Time（使用ParameterCalculator）
  const calculateMTT = (timeData, signalData) => {
    if (!timeData || !signalData || timeData.length === 0) return 0.0;
    
    try {
      parameterCalculator.setTimeArray(timeData);
      const extendedParams = parameterCalculator.calculateExtendedParameters(signalData, timeData);
      return extendedParams.mtt;
    } catch (error) {
      console.error('MTT计算失败:', error);
      return 0.0;
    }
  };

  // 计算平均HU值 (Hounsfield Unit)（使用ParameterCalculator）
  const calculateHU = (signalData) => {
    if (!signalData || signalData.length === 0) return 0.0;
    
    try {
      return parameterCalculator.calculateHU(signalData);
    } catch (error) {
      console.error('HU计算失败:', error);
      return 0.0;
    }
  };

  // 计算脑血流量 (CBF) - Cerebral Blood Flow（使用ParameterCalculator）
  const calculateCBF = (timeData, signalData) => {
    if (!timeData || !signalData || timeData.length === 0) return 0.0;
    
    try {
      parameterCalculator.setTimeArray(timeData);
      const extendedParams = parameterCalculator.calculateExtendedParameters(signalData, timeData);
      return extendedParams.cbf;
    } catch (error) {
      console.error('CBF计算失败:', error);
      return 0.0;
    }
  };

  // 计算脑血容量 (CBV) - Cerebral Blood Volume（使用ParameterCalculator）
  const calculateCBV = (timeData, signalData) => {
    if (!timeData || !signalData || timeData.length === 0) return 0.0;
    
    try {
      parameterCalculator.setTimeArray(timeData);
      const extendedParams = parameterCalculator.calculateExtendedParameters(signalData, timeData);
      return extendedParams.cbv;
    } catch (error) {
      console.error('CBV计算失败:', error);
      return 0.0;
    }
  };

  // 创建标注数据（供内部和外部使用）
  const createAnnotationsData = (processingMethod = null, arterialInputPoint = null) => {
    try {
      // 构建保存数据
          const saveData = {
      exportInfo: {
        timestamp: new Date().toISOString(),
        version: '1.0',
        description: 'TDC分析标注结果',
        totalMarkers: markers.length,
        visibleMarkers: markers.filter(m => m.visible !== false).length,
        // 帧范围信息
        frameRange: {
          start: frameRange.start,
          end: frameRange.end,
          totalFrames: frameRange.end - frameRange.start + 1,
          description: `TDC分析使用的帧范围: 第${frameRange.start}帧到第${frameRange.end}帧`
        },
        // 新增：计算方法信息
        processingMethod: processingMethod || 'normal',
        arterialInputPoint: arterialInputPoint ? {
          x: arterialInputPoint.x,
          y: arterialInputPoint.y,
          description: '最大斜率法使用的动脉输入点'
        } : null
      },
        imageInfo: dicomData ? {
          totalFrames: dicomData.images?.length || 0,
          imageSize: dicomData.images?.[0] ? {
            width: dicomData.images[0].columns || dicomData.images[0].width,
            height: dicomData.images[0].rows || dicomData.images[0].height
          } : null,
          // DICOM标识信息
          studyUID: dicomData.images?.[0]?.studyInstanceUID || dicomData.metadata?.studyInstanceUID || 'N/A',
          seriesUID: dicomData.images?.[0]?.seriesInstanceUID || dicomData.seriesInstanceUID || 'N/A',
          // 患者信息
          patientInfo: {
            patientName: dicomData.metadata?.patientName || dicomData.images?.[0]?.patientName || 'N/A',
            patientID: dicomData.metadata?.patientId || dicomData.images?.[0]?.patientId || 'N/A',
            patientBirthDate: dicomData.metadata?.patientBirthDate || dicomData.images?.[0]?.patientBirthDate || 'N/A',
            patientSex: dicomData.metadata?.patientSex || dicomData.images?.[0]?.patientSex || 'N/A'
          },
          // 检查信息
          studyInfo: {
            studyDate: dicomData.metadata?.studyDate || dicomData.images?.[0]?.studyDate || 'N/A',
            studyTime: dicomData.metadata?.studyTime || dicomData.images?.[0]?.studyTime || 'N/A',
            studyDescription: dicomData.metadata?.studyDescription || dicomData.images?.[0]?.studyDescription || 'N/A',
            accessionNumber: dicomData.metadata?.accessionNumber || dicomData.images?.[0]?.accessionNumber || 'N/A'
          },
          // 序列信息
          seriesInfo: {
            seriesDescription: dicomData.metadata?.seriesDescription || dicomData.images?.[0]?.seriesDescription || 'N/A',
            seriesNumber: dicomData.metadata?.seriesNumber || dicomData.images?.[0]?.seriesNumber || 'N/A',
            modality: dicomData.metadata?.modality || dicomData.images?.[0]?.modality || 'N/A',
            bodyPartExamined: dicomData.metadata?.bodyPartExamined || dicomData.images?.[0]?.bodyPartExamined || 'N/A'
          },
          // 医院信息
          institutionInfo: {
            institutionName: dicomData.metadata?.institutionName || dicomData.images?.[0]?.institutionName || 'N/A',
            institutionAddress: dicomData.metadata?.institutionAddress || dicomData.images?.[0]?.institutionAddress || 'N/A',
            stationName: dicomData.metadata?.stationName || dicomData.images?.[0]?.stationName || 'N/A',
            institutionalDepartmentName: dicomData.metadata?.departmentName || dicomData.images?.[0]?.departmentName || 'N/A'
          },
          // 设备厂家信息
          equipmentInfo: {
            manufacturer: dicomData.metadata?.manufacturer || dicomData.images?.[0]?.manufacturer || 'N/A',
            manufacturerModelName: dicomData.metadata?.manufacturerModelName || dicomData.images?.[0]?.manufacturerModelName || 'N/A',
            deviceSerialNumber: dicomData.metadata?.deviceSerialNumber || dicomData.images?.[0]?.deviceSerialNumber || 'N/A',
            softwareVersions: dicomData.metadata?.softwareVersions || dicomData.images?.[0]?.softwareVersions || 'N/A'
          },
          // 技术参数
          acquisitionInfo: {
            pixelSpacing: dicomData.metadata?.pixelSpacing || dicomData.images?.[0]?.pixelSpacing || 'N/A',
            sliceThickness: dicomData.metadata?.sliceThickness || dicomData.images?.[0]?.sliceThickness || 'N/A',
            repetitionTime: dicomData.metadata?.repetitionTime || dicomData.images?.[0]?.repetitionTime || 'N/A',
            echoTime: dicomData.metadata?.echoTime || dicomData.images?.[0]?.echoTime || 'N/A',
            flipAngle: dicomData.metadata?.flipAngle || dicomData.images?.[0]?.flipAngle || 'N/A'
          },
          // 多帧信息
          multiFrameInfo: dicomData.isMultiFrame ? {
            isMultiFrame: true,
            numberOfFrames: dicomData.metadata?.numberOfFrames || dicomData.images?.length || 0,
            frameTime: dicomData.metadata?.frameTime || 'N/A',
            temporalResolution: dicomData.metadata?.temporalResolution || 'N/A',
            frameRate: dicomData.metadata?.frameRate || 'N/A'
          } : {
            isMultiFrame: false
          }
        } : null,
        annotations: markers.map(marker => {
          // 获取对应的TDC数据
          const tdcData = chartData?.find(data => data.id === marker.id);
          
          // 基础标记信息
          const annotation = {
            id: marker.id,
            name: marker.name,
            type: marker.type,
            color: marker.color,
            visible: marker.visible !== false,
            coordinates: null,
            tdcData: null,
            timeData: null,
            parameters: null
          };

          // 添加坐标信息
          if (marker.type === 'point') {
            annotation.coordinates = {
              x: marker.x,
              y: marker.y
            };
          } else if (marker.type === 'region') {
            annotation.coordinates = {
              x: marker.region.x,
              y: marker.region.y,
              width: marker.region.width,
              height: marker.region.height
            };
          } else if (marker.type === 'contour') {
            annotation.coordinates = {
              path: marker.contour.path,
              bounds: marker.contour.bounds
            };
          }

          // 添加TDC数据和参数
          if (tdcData) {
            annotation.tdcData = tdcData.signalData;
            annotation.timeData = tdcData.timeData;
            annotation.parameters = {
              peak: tdcData.statistics.peak, // 已经是Float类型
              TTP: tdcData.statistics.ttp,   // 达峰时间，已经是Float类型
              AUC: tdcData.statistics.auc,   // 曲线下面积，已经是Float类型
              MTT: calculateMTT(tdcData.timeData, tdcData.signalData), // 平均通过时间，返回Float
              HU: calculateHU(tdcData.signalData), // 平均HU值，返回Float
              CBF: calculateCBF(tdcData.timeData, tdcData.signalData), // 脑血流量
              CBV: calculateCBV(tdcData.timeData, tdcData.signalData)  // 脑血容量
            };
          }

          return annotation;
        })
      };

      return saveData;
    } catch (error) {
      console.error('创建标注数据失败:', error);
      throw error;
    }
  };

  // 保存标注结果到JSON文件 - 完整版本
  const handleSaveAnnotations = () => {
    if (markers.length === 0) {
      alert('没有标记可以保存');
      return;
    }

    try {
      const saveData = createAnnotationsData();

      // 生成文件名
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
      const filename = `TDC_Annotations_${timestamp}.json`;

      // 创建并下载文件
      const blob = new Blob([JSON.stringify(saveData, null, 2)], { 
        type: 'application/json' 
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      alert(`标注结果已保存为 ${filename}`);
    } catch (error) {
      console.error('保存标注结果失败:', error);
      alert('保存失败，请重试');
    }
  };

  return (
    <div className="tdc-markers-panel-container">
      <div className="marker-list">
        <div className="marker-list-header">
          <h4>标记列表</h4>
          {markers.length > 0 && (
            <div className="header-controls">
              <div className="batch-controls">
                <label className="batch-checkbox">
                  <input
                    type="checkbox"
                    checked={markers.filter(m => m.visible !== false).length === markers.length}
                    onChange={(e) => handleBatchVisibility(e.target.checked)}
                    title="显示/隐藏所有标记"
                  />
                  <span className="checkbox-label">
                    👁️ 显示全部标记
                  </span>
                </label>
              </div>
              <button
                className="clear-all-btn"
                onClick={onClearAllMarkers}
                title="清空所有标记"
              >
                🗑️ 清空标记
              </button>
              <button
                className="save-annotations-btn"
                onClick={handleSaveAnnotations}
                title="保存标注结果到JSON文件"
              >
                💾 保存标注
              </button>
            </div>
          )}
        </div>
        
        {markers.length === 0 ? (
          <div className="empty-markers">
            <span>暂无标记</span>
          </div>
        ) : (
          <div className="markers-container">
            {markers.map(marker => (
              <div
                key={marker.id}
                className={`marker-item ${selectedMarker === marker.id ? 'selected' : ''}`}
                onClick={() => setSelectedMarker(marker.id)}
              >
                <div className="marker-header">
                  <div 
                    className="marker-color" 
                    style={{ backgroundColor: marker.color }}
                  />
                  
                  {/* 标记名称显示/编辑 */}
                  {editingMarker === marker.id ? (
                    <div className="marker-name-edit">
                      <input
                        type="text"
                        value={editingName}
                        onChange={(e) => setEditingName(e.target.value)}
                        onKeyDown={(e) => handleNameInputKeyDown(e, marker.id)}
                        onBlur={() => handleSaveEditName(marker.id)}
                        className="name-input"
                        autoFocus
                        placeholder="输入标记名称"
                      />
                      <div className="edit-actions">
                        <button
                          className="save-btn"
                          onClick={() => handleSaveEditName(marker.id)}
                          title="保存名称 (Enter)"
                        >
                          ✓
                        </button>
                        <button
                          className="cancel-btn"
                          onClick={handleCancelEditName}
                          title="取消编辑 (ESC)"
                        >
                          ×
                        </button>
                      </div>
                    </div>
                  ) : (
                    <span 
                      className="marker-name"
                      onClick={() => handleStartEditName(marker.id, marker.name)}
                      title="点击编辑名称"
                    >
                      {marker.name}
                    </span>
                  )}
                  
                  <div className="visibility-controls">
                    <button
                      className={`visibility-btn ${marker.visible !== false ? 'active' : ''}`}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleToggleVisibility(marker.id);
                      }}
                      title="显示/隐藏标记"
                    >
                      {marker.visible !== false ? '👁️' : '🙈'}
                    </button>
                  </div>
                  
                  <button
                    className="delete-btn"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDeleteMarker(marker.id);
                    }}
                  >
                    ×
                  </button>
                </div>
                
                <div className="marker-info">
                  <span className="marker-type">
                    {marker.type === 'point' ? '点标记' : 
                     marker.type === 'region' ? '矩形区域' : 
                     marker.type === 'contour' ? '自由轮廓' : '区域标记'}
                  </span>
                  {marker.type === 'point' && (
                    <span className="marker-coords">
                      ({marker.x}, {marker.y})
                    </span>
                  )}
                  {marker.type === 'region' && (
                    <span className="marker-coords">
                      {marker.region.width}×{marker.region.height}
                    </span>
                  )}
                  {marker.type === 'contour' && (
                    <span className="marker-coords">
                      {marker.contour.path.length} 点轮廓
                    </span>
                  )}
                </div>

                {chartData?.find(data => data.id === marker.id) && (
                  <div className="marker-stats">
                    <div className="stat-item">
                      <span className="stat-label">峰值</span>
                      <span className="stat-value">
                        {chartData.find(data => data.id === marker.id)?.statistics.peak}
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">TTP</span>
                      <span className="stat-value">
                        {chartData.find(data => data.id === marker.id)?.statistics.ttp}s
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">AUC</span>
                      <span className="stat-value">
                        {chartData.find(data => data.id === marker.id)?.statistics.auc}
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">MTT</span>
                      <span className="stat-value">
                        {(() => {
                          const data = chartData.find(data => data.id === marker.id);
                          return data ? calculateMTT(data.timeData, data.signalData).toFixed(2) : '0.00'
                        })()}s
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">HU</span>
                      <span className="stat-value">
                        {(() => {
                          const data = chartData.find(data => data.id === marker.id);
                          return data ? calculateHU(data.signalData).toFixed(1) : '0.0'
                        })()}
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">CBF</span>
                      <span className="stat-value">
                        {(() => {
                          const data = chartData.find(data => data.id === marker.id);
                          return data ? calculateCBF(data.timeData, data.signalData).toFixed(1) : '0.0'
                        })()}
                      </span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">CBV</span>
                      <span className="stat-value">
                        {(() => {
                          const data = chartData.find(data => data.id === marker.id);
                          return data ? calculateCBV(data.timeData, data.signalData).toFixed(1) : '0.0'
                        })()}
                      </span>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// 导出createAnnotationsData方法供其他服务使用
export const createTdcAnnotationsData = (markers, chartData, dicomData, processingMethod = null, arterialInputPoint = null, frameRange = { start: 1, end: 1 }) => {
  // 动态导入ParameterCalculator以避免循环依赖
  const ParameterCalculator = require('../services/ParameterCalculator').default;
  const parameterCalculator = new ParameterCalculator();

  // 计算平均通过时间 (MTT) - Mean Transit Time（使用ParameterCalculator）
  const calculateMTT = (timeData, signalData) => {
    if (!timeData || !signalData || timeData.length === 0) return 0.0;
    
    try {
      parameterCalculator.setTimeArray(timeData);
      const extendedParams = parameterCalculator.calculateExtendedParameters(signalData, timeData);
      return extendedParams.mtt;
    } catch (error) {
      console.error('MTT计算失败:', error);
      return 0.0;
    }
  };

  // 计算平均HU值 (Hounsfield Unit)（使用ParameterCalculator）
  const calculateHU = (signalData) => {
    if (!signalData || signalData.length === 0) return 0.0;
    
    try {
      return parameterCalculator.calculateHU(signalData);
    } catch (error) {
      console.error('HU计算失败:', error);
      return 0.0;
    }
  };

  // 计算脑血流量 (CBF) - Cerebral Blood Flow（使用ParameterCalculator）
  const calculateCBF = (timeData, signalData) => {
    if (!timeData || !signalData || timeData.length === 0) return 0.0;
    
    try {
      parameterCalculator.setTimeArray(timeData);
      const extendedParams = parameterCalculator.calculateExtendedParameters(signalData, timeData);
      return extendedParams.cbf;
    } catch (error) {
      console.error('CBF计算失败:', error);
      return 0.0;
    }
  };

  // 计算脑血容量 (CBV) - Cerebral Blood Volume（使用ParameterCalculator）
  const calculateCBV = (timeData, signalData) => {
    if (!timeData || !signalData || timeData.length === 0) return 0.0;
    
    try {
      parameterCalculator.setTimeArray(timeData);
      const extendedParams = parameterCalculator.calculateExtendedParameters(signalData, timeData);
      return extendedParams.cbv;
    } catch (error) {
      console.error('CBV计算失败:', error);
      return 0.0;
    }
  };

  try {
    // 构建保存数据
    const saveData = {
      exportInfo: {
        timestamp: new Date().toISOString(),
        version: '1.0',
        description: 'TDC分析标注结果',
        totalMarkers: markers.length,
        visibleMarkers: markers.filter(m => m.visible !== false).length,
        // 帧范围信息
        frameRange: {
          start: frameRange.start,
          end: frameRange.end,
          totalFrames: frameRange.end - frameRange.start + 1,
          description: `TDC分析使用的帧范围: 第${frameRange.start}帧到第${frameRange.end}帧`
        },
        // 新增：计算方法信息
        processingMethod: processingMethod || 'normal',
        arterialInputPoint: arterialInputPoint ? {
          x: arterialInputPoint.x,
          y: arterialInputPoint.y,
          description: '最大斜率法使用的动脉输入点'
        } : null
      },
      imageInfo: dicomData ? {
        totalFrames: dicomData.images?.length || 0,
        imageSize: dicomData.images?.[0] ? {
          width: dicomData.images[0].columns || dicomData.images[0].width,
          height: dicomData.images[0].rows || dicomData.images[0].height
        } : null,
        // DICOM标识信息
        studyUID: dicomData.images?.[0]?.studyInstanceUID || dicomData.metadata?.studyInstanceUID || 'N/A',
        seriesUID: dicomData.images?.[0]?.seriesInstanceUID || dicomData.seriesInstanceUID || 'N/A',
        // 患者信息
        patientInfo: {
          patientName: dicomData.metadata?.patientName || dicomData.images?.[0]?.patientName || 'N/A',
          patientID: dicomData.metadata?.patientId || dicomData.images?.[0]?.patientId || 'N/A',
          patientBirthDate: dicomData.metadata?.patientBirthDate || dicomData.images?.[0]?.patientBirthDate || 'N/A',
          patientSex: dicomData.metadata?.patientSex || dicomData.images?.[0]?.patientSex || 'N/A'
        },
        // 检查信息
        studyInfo: {
          studyDate: dicomData.metadata?.studyDate || dicomData.images?.[0]?.studyDate || 'N/A',
          studyTime: dicomData.metadata?.studyTime || dicomData.images?.[0]?.studyTime || 'N/A',
          studyDescription: dicomData.metadata?.studyDescription || dicomData.images?.[0]?.studyDescription || 'N/A',
          accessionNumber: dicomData.metadata?.accessionNumber || dicomData.images?.[0]?.accessionNumber || 'N/A'
        },
        // 序列信息
        seriesInfo: {
          seriesDescription: dicomData.metadata?.seriesDescription || dicomData.images?.[0]?.seriesDescription || 'N/A',
          seriesNumber: dicomData.metadata?.seriesNumber || dicomData.images?.[0]?.seriesNumber || 'N/A',
          modality: dicomData.metadata?.modality || dicomData.images?.[0]?.modality || 'N/A',
          bodyPartExamined: dicomData.metadata?.bodyPartExamined || dicomData.images?.[0]?.bodyPartExamined || 'N/A'
        },
        // 医院信息
        institutionInfo: {
          institutionName: dicomData.metadata?.institutionName || dicomData.images?.[0]?.institutionName || 'N/A',
          institutionAddress: dicomData.metadata?.institutionAddress || dicomData.images?.[0]?.institutionAddress || 'N/A',
          stationName: dicomData.metadata?.stationName || dicomData.images?.[0]?.stationName || 'N/A',
          institutionalDepartmentName: dicomData.metadata?.departmentName || dicomData.images?.[0]?.departmentName || 'N/A'
        },
        // 设备厂家信息
        equipmentInfo: {
          manufacturer: dicomData.metadata?.manufacturer || dicomData.images?.[0]?.manufacturer || 'N/A',
          manufacturerModelName: dicomData.metadata?.manufacturerModelName || dicomData.images?.[0]?.manufacturerModelName || 'N/A',
          deviceSerialNumber: dicomData.metadata?.deviceSerialNumber || dicomData.images?.[0]?.deviceSerialNumber || 'N/A',
          softwareVersions: dicomData.metadata?.softwareVersions || dicomData.images?.[0]?.softwareVersions || 'N/A'
        },
        // 技术参数
        acquisitionInfo: {
          pixelSpacing: dicomData.metadata?.pixelSpacing || dicomData.images?.[0]?.pixelSpacing || 'N/A',
          sliceThickness: dicomData.metadata?.sliceThickness || dicomData.images?.[0]?.sliceThickness || 'N/A',
          repetitionTime: dicomData.metadata?.repetitionTime || dicomData.images?.[0]?.repetitionTime || 'N/A',
          echoTime: dicomData.metadata?.echoTime || dicomData.images?.[0]?.echoTime || 'N/A',
          flipAngle: dicomData.metadata?.flipAngle || dicomData.images?.[0]?.flipAngle || 'N/A'
        },
        // 多帧信息
        multiFrameInfo: dicomData.isMultiFrame ? {
          isMultiFrame: true,
          numberOfFrames: dicomData.metadata?.numberOfFrames || dicomData.images?.length || 0,
          frameTime: dicomData.metadata?.frameTime || 'N/A',
          temporalResolution: dicomData.metadata?.temporalResolution || 'N/A',
          frameRate: dicomData.metadata?.frameRate || 'N/A'
        } : {
          isMultiFrame: false
        }
      } : null,
      annotations: markers.map(marker => {
        // 获取对应的TDC数据
        const tdcData = chartData?.find(data => data.id === marker.id);
        
        // 基础标记信息
        const annotation = {
          id: marker.id,
          name: marker.name,
          type: marker.type,
          color: marker.color,
          visible: marker.visible !== false,
          coordinates: null,
          tdcData: null,
          timeData: null,
          parameters: null
        };

        // 添加坐标信息
        if (marker.type === 'point') {
          annotation.coordinates = {
            x: marker.x,
            y: marker.y
          };
        } else if (marker.type === 'region') {
          annotation.coordinates = {
            x: marker.region.x,
            y: marker.region.y,
            width: marker.region.width,
            height: marker.region.height
          };
        } else if (marker.type === 'contour') {
          annotation.coordinates = {
            path: marker.contour.path,
            bounds: marker.contour.bounds
          };
        }

        // 添加TDC数据和参数
        if (tdcData) {
          annotation.tdcData = tdcData.signalData;
          annotation.timeData = tdcData.timeData;
          annotation.parameters = {
            peak: tdcData.statistics.peak, // 已经是Float类型
            TTP: tdcData.statistics.ttp,   // 达峰时间，已经是Float类型
            AUC: tdcData.statistics.auc,   // 曲线下面积，已经是Float类型
            MTT: calculateMTT(tdcData.timeData, tdcData.signalData), // 平均通过时间，返回Float
            HU: calculateHU(tdcData.signalData), // 平均HU值，返回Float
            CBF: calculateCBF(tdcData.timeData, tdcData.signalData), // 脑血流量
            CBV: calculateCBV(tdcData.timeData, tdcData.signalData)  // 脑血容量
          };
        }

        return annotation;
      })
    };

    return saveData;
  } catch (error) {
    console.error('创建TDC标注数据失败:', error);
    throw error;
  }
};

export default TDCMarkersPanel; 